# -*- coding: utf-8 -*-
import hashlib
from datetime import datetime
from app import app, login_manager
from setting import app_name
from models import Post, User


def create_signature(ticket, noncestr, timestamp, url):
    str = 'jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s' % (ticket, noncestr, timestamp, url)
    return hashlib.sha1(str).hexdigest()


@app.template_filter('dateformat')
def datetime_format(value):
    return value.strftime('%Y/%m/%d')


@app.context_processor
def site_name():
    return dict(site_name=app_name)


@app.context_processor
def latest_posts():
    latest = Post.query.order_by(Post.create_time.desc())[0:3]
    return dict(latest=latest)


@app.context_processor
def copy_right():
    return dict(copy_right=datetime.now().year)


@login_manager.request_loader
def load_user_from_request(request):

    # first, try to login using the api_key url arg
    api_key = request.args.get('api_key')
    if api_key:
        user = User.query.filter_by(api_key=api_key).first()
        if user:
            return user

    # next, try to login using Basic Auth
    api_key = request.headers.get('Authorization')
    if api_key:
        api_key = api_key.replace('Basic ', '', 1)
        try:
            api_key = base64.b64decode(api_key)
        except TypeError:
            pass
        user = User.query.filter_by(api_key=api_key).first()
        if user:
            return user

    # finally, return None if both methods did not login the user
    return None
